program delphi_config_get;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  IdHTTP,
  IdObjs,
  IdAuthentication,
  Dialogs;

function dopost(AFormat, AMethod, ARequest: string): string;
var
  IdHTTP: TIdHTTP;
  RBody: TIdStringStream;
begin
  IdHTTP := TIdHTTP.Create();
  RBody := TIdStringStream.Create(ARequest);
  try
    if AFormat = 'json' then
    begin
      IdHTTP.Request.Accept := 'text/javascript';
      IdHTTP.Request.ContentType := 'application/json';
      IdHTTP.Request.ContentEncoding := 'utf-8';
    end
    else
    begin
      IdHTTP.Request.Accept := 'text/xml';
      IdHTTP.Request.ContentType := 'text/xml';
      IdHTTP.Request.ContentEncoding := 'utf-8';
    end;
    IdHTTP.Request.BasicAuthentication := True;
    IdHTTP.Request.Authentication := TIdBasicAuthentication.Create;
    IdHTTP.Request.Authentication.Username := 'admin';
    IdHTTP.Request.Authentication.Password := 'admin';
    Result := IdHTTP.Post('http://127.0.0.1:8080/api/' + AMethod, RBody);
  finally
    FreeAndNil(RBody);
    FreeAndNil(IdHTTP);
  end;
end;

function json_config_get(varname: string): string;
var
  body: string;
  response: string;
begin
  body := '{"varname":"' + varname + '"}';
  response := dopost('json', 'config/get', body);
  // The response has the following format :
  // {"result":"SOMETHING WE ARE INTERESTED IN"}
  Result := Copy(response, 13, Length(response) - 14);
end;

function xml_config_get(varname: string): string;
var
  body: string;
  response: string;
begin
  body := '<parameters><varname>' + varname + '</varname></parameters>';
  response := dopost('xml', 'config/get', body);
  // The response has the following format :
  // <result>THE RESULT</result>
  Result := Copy(response, 9, Length(response) - 17);
end;

begin
  try
    ShowMessage(json_config_get('company_name'));
    ShowMessage(xml_config_get('company_name'));
  except
    on E: Exception do
      ShowMessage(E.Message);
  end;
end.
